package com.iqiyi.pps.epg.core.dao.auth;


import com.iqiyi.pps.epg.core.dao.base.HibernateDao;
import com.iqiyi.pps.epg.core.model.auth.Role;
import com.iqiyi.pps.epg.core.model.auth.SysUser;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Role的数据库操作类
 */
@Component
public class RoleDao extends HibernateDao<Role, Long> {

	private static final String QUERY_USER_BY_ROLEID = "select u from SysUser u left join u.roleList r where r.id=?";

	/**
	 * 重载函数,因为Role中没有建立与User的关联,因此需要以较低效率的方式进行删除User与Role的多对多中间表.
     * @param id 主键
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void delete(Long id) {
		Role role = get(id);
		//查询出拥有该角色的用户,并删除该用户的角色.
		List<SysUser> users = createQuery(QUERY_USER_BY_ROLEID, role.getId()).list();
		for (SysUser u : users) {
			u.getRoleList().remove(role);
		}
		super.delete(role);
	}

    public List<SysUser> listUserByRoleId(Long id) {
        //查询出拥有该角色的用户,并删除该用户的角色.
        return  createQuery(QUERY_USER_BY_ROLEID, id).list();
    }
}
